package com.hxx.controller;

import lombok.SneakyThrows;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import org.springframework.core.io.FileSystemResource;


@RestController
public class QinwenController4 {

    @Autowired
    private EmbeddingModel embeddingModel;

    @SneakyThrows
    @PostMapping(value = "/readMulipartFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String readMulipartFile(MultipartFile filePath) {
        try {
            //读取IO流文件
            InputStreamResource resource = new InputStreamResource(filePath.getInputStream());
            //使用TikaDocumentReader读取文件内容到Document列表中
            List<Document> documents = new TikaDocumentReader(resource).read();
            //将Document列表转换为内容字符串列表，并以字符串形式返回
            return documents.stream().map(Document::getContent).toList().toString();

        }catch (Exception e){
            //打印异常堆栈跟踪，用于调试和日志记录
            e.printStackTrace();
        }
        //如果发生异常，返回null
        return "读取失败";
    }
    @SneakyThrows
    @GetMapping(value = "/qinwen3")
    public String readLocalFile() {
        try {
            //使用TikaDocumentReader读取文件内容到Document列表中
            List<Document> documents = new TikaDocumentReader(new FileSystemResource("d:/zmx/hxx.txt")).read();
            //将Document列表中的内容拼接成一个字符串返回
            return documents
                    .stream()
                    .map(Document::getContent)
                    .toList()
                    .toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "读取失败";
    }

}
